<template>
  <div id="index">
    <div class="app-container"
      id="container">

      <el-form ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="right">
        <div class="product-div">
          <div class="product-header">
            <em style="font-size: 18px;font-style: normal;"
              class="big_title_style">基本信息</em>
          </div>

          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="项目名称"
                prop="itemName">
                <el-input v-model="form.itemName"
                  placeholder="请输入项目名称"
                  clearable
                  maxlength="50"
                  show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="7">
              <el-form-item label="服务项目分类"
                prop="categoryUids"
                style="width: 100%;">
                <el-cascader :props="{ checkStrictly: true }"
                  style="width: 100%;"
                  v-model="form.categoryUids"
                  :options="categoryOptions"
                  clearable
                  filterable>
                </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-appendHide">元</div>
            </el-col>
            <el-col :span="7">
              <el-form-item label="服务项目类别"
                prop="itemType"
                style="width: 100%;">
                <el-select style="width: 100%;"
                  v-model="form.itemType"
                  placeholder="请选择类别"
                  clearable
                  size="small"
                  @change="itemTypeChange">
                  <el-option v-for="dict in itemTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-appendHide">元</div>
            </el-col>

            <el-col :span="7">
              <el-form-item label="菠萝派"
                prop="itemBoluoHuaPrice">
                <el-input-number style="width:100%;"
                  :controls="false"
                  :precision="0"
                  :step="0"
                  :min="0"
                  :max="9999999"
                  v-model="form.itemBoluoHuaPriceStr"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-append">个</div>
            </el-col>

          </el-row>

          <el-row :gutter="20">
            <el-col :span="7">
              <el-form-item label="面价"
                :required="true">
                <el-input-number style="width:100%;"
                  :precision="2"
                  :controls="false"
                  :step="0.1"
                  :min="0"
                  :max="9999999"
                  v-model="form.itemPriceStr">
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-append">元</div>
            </el-col>

            <el-col :span="7">
              <el-form-item label="活动价格"
                prop="itemFavorablePrice">
                <el-input-number style="width:100%;"
                  :precision="2"
                  :controls="false"
                  :step="0.1"
                  :min="0"
                  :max="9999999"
                  v-model="form.itemFavorablePriceStr"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-append">元</div>
            </el-col>

            <el-col :span="7">
              <el-form-item label="美容师耗卡"
                :required="true">
                <el-input-number style="width:100%;"
                  :precision="2"
                  :controls="false"
                  :step="0.1"
                  :min="0.01"
                  :max="9999999"
                  v-model="form.itemSettlementPriceStr"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-append">元</div>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="7">
              <el-form-item label="是否是主项目"
                prop="isMaster"
                style="width: 100%;">
                <el-select style="width: 100%;"
                  v-model="form.isMaster"
                  placeholder="请选择"
                  clearable
                  size="small">
                  <el-option v-for="dict in isMasterOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="1">
              <div class="div-appendHide">%</div>
            </el-col>

            <el-col :span="7">
              <el-form-item label="门店销售分成"
                :required="true">
                <el-input-number style="width:100%;"
                  :controls="false"
                  :precision="0"
                  :step="0"
                  :min="0"
                  :max="100"
                  v-model="form.itemSalePercent"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-append">%</div>
            </el-col>

            <el-col :span="7">
              <el-form-item label="门店服务分成"
                :required="true">
                <el-input-number style="width:100%;"
                  :controls="false"
                  :precision="0"
                  :step="0"
                  :min="0"
                  :max="100"
                  v-model="form.itemServicePercent"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-append">%</div>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="7">
              <el-form-item label="单服务耗时"
                prop="itemServiceDuration">
                <el-input style="width:100%;"
                  v-model="form.itemServiceDuration"
                  @input="form.itemServiceDuration = form.itemServiceDuration.replace(/^(0+)|[^\d]+/g, '')"
                  placeholder=""
                  clearable
                  maxlength="3"
                  show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-append">分钟</div>
            </el-col>

            <el-col :span="7">
              <el-form-item label="叠加服务耗时"
                prop="itemComposeDuration">
                <el-input style="width:100%;"
                  v-model="form.itemComposeDuration"
                  @input="form.itemComposeDuration = form.itemComposeDuration.replace(/^(0+)|[^\d]+/g, '')"
                  placeholder=""
                  clearable
                  maxlength="3"
                  show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-append">分钟</div>
            </el-col>
            <!-- <el-col :span="7">
              <el-form-item label="护理周期" prop="cycleDay">
                <el-input style="width:100%;" v-model="form.cycleDay"
                  @input="form.cycleDay = form.cycleDay.replace(/^(0+)|[^\d]+/g, '')" placeholder="" clearable
                  maxlength="3" show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-append">天</div>
            </el-col> -->
          </el-row>

          <el-row :gutter="24">
            <!-- <el-col :span="7">
              <el-form-item label="有效时间" prop="expireDay">
                <el-input-number style="width:100%;" :controls="false" :precision="0" :step="0" :min="0" :max="9999999"
                  v-model="form.expireDay"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-append">天</div>
            </el-col> -->

            <el-col :span="24">
              <el-form-item label="过期类型">
                <el-radio-group v-model="form.expireDayRadio">
                  <el-radio :label="-1">长期有效</el-radio>
                  <el-radio :label="0">有效时间</el-radio>
                  <el-radio :label="2">指定时间</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24"
            v-if="form.expireDayRadio == 0">
            <el-col :span="7">
              <el-form-item label="有效时间"
                prop="expireDay">
                <el-input-number style="width:100%;"
                  :controls="false"
                  :precision="0"
                  :step="0"
                  :min="0"
                  :max="9999999"
                  v-model="form.expireDay"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="div-append">天</div>
            </el-col>
          </el-row>

          <el-row :gutter="24"
            v-if="form.expireDayRadio == 2">
            <el-col :span="7">
              <el-form-item label="指定时间"
                prop="expireDate">
                <el-date-picker value-format="yyyy-MM-dd"
                  v-model="form.expireDate"
                  type="date"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>

          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="适用门店">
                <el-checkbox-group v-model="form.serviceTypes"
                  @change="choiceServiceCheckbox">
                  <el-checkbox :disabled='disabledType(item.dictValue)'
                    :key="index"
                    v-for="(item, index) in serviceTypesList"
                    :label="item.dictValue">
                    {{ item.dictLabel }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="选择">
                <el-checkbox-group v-model="form.checkList">
                  <el-checkbox label="isCommon"
                    @change="choiceCheckboxStroe">指定门店</el-checkbox>
                  <el-checkbox label="isLockDevice"
                    @change="choiceCheckboxDevice">需要设备</el-checkbox>
                  <el-checkbox label="isSubgift">支持转赠</el-checkbox>
                  <el-checkbox label="isShow">前端展示</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="门店列表"
            v-if="existValue('isCommon') > 0"
            prop="isCommon">
            <el-button class="button-new-tag"
              size="small"
              type="primary"
              @click="selectCommodity">选择门店</el-button>
            <selected ref="childStore"
              style="margin-top: 10px;"
              v-if="selectedDataStore.length > 0"
              :selectedData="selectedDataStore">
            </selected>
          </el-form-item>

          <el-form-item label="设备列表"
            v-if="existValue('isLockDevice') > 0"
            prop="isLockDevice">
            <el-button class="button-new-tag"
              size="small"
              type="primary"
              @click="selectCommodityDevice">选择设备
            </el-button>
            <selectedDevice ref="childDevice"
              style="margin-top: 10px;"
              v-if="selectedDataDevice.length > 0"
              :selectedData="selectedDataDevice">
            </selectedDevice>
          </el-form-item>

          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="支付方式">
                <el-checkbox-group v-model="form.checkListPay">
                  <el-checkbox label="isUseBoluoGoldCoin">菠萝金币</el-checkbox>
                  <el-checkbox label="isUseBoluoSilverCoin">菠萝银币</el-checkbox>
                  <el-checkbox label="isUseCoupon">优惠券</el-checkbox>
                  <el-checkbox label="isUseMemberDiscount"
                    @change="choiceCheckboxMember">会员折扣</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="7">
              <el-form-item label="折扣等级"
                v-if="existValuePay('isUseMemberDiscount') > 0"
                prop="isUseMemberDiscount">
                <el-select style="width: 100%;"
                  v-model="form.memberLevel"
                  placeholder="请选择等级"
                  clearable
                  size="small">
                  <el-option v-for="dict in levelOptions"
                    :key="dict.customerGrade"
                    :label="dict.levelNameStr"
                    :value="dict.customerGrade" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="22">
              <el-form-item label="营销标签"
                prop="itemTags"
                style="width: 100%;">
                <el-tag style="margin: 5px;"
                  :key="tag"
                  v-for="tag in form.itemTagsArrayYx"
                  closable
                  :disable-transitions="false"
                  @close="handleCloseYx(tag)">
                  {{ tag }}
                </el-tag>
                <el-input style="width: 200px;"
                  class="input-new-tag"
                  v-if="inputVisibleYx"
                  v-model="inputValueYx"
                  ref="saveTagInputYx"
                  size="small"
                  @keyup.enter.native="handleInputConfirmYx"
                  @blur="handleInputConfirmYx">
                </el-input>
                <el-button v-if="2>this.form.itemTagsArrayYx.length"
                  class="button-new-tag"
                  size="small"
                  @click="showInputYx">+新增标签
                </el-button>

              </el-form-item>
            </el-col>

          </el-row>

          <el-row :gutter="20">
            <el-col :span="22">
              <el-form-item label="标签集合"
                prop="itemTags"
                style="width: 100%;">
                <el-tag style="margin: 5px;"
                  :key="tag"
                  v-for="tag in form.itemTagsArray"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag)">
                  {{ tag }}
                </el-tag>
                <el-input style="width: 200px;"
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm">
                </el-input>
                <el-button v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput">+新增标签
                </el-button>

              </el-form-item>
            </el-col>

          </el-row>

          <el-row :gutter="20">
            <el-col :span="22">
              <el-form-item label="属性集合"
                prop="itemAttributeArray"
                style="width: 100%;">
                <el-tag style="margin: 5px;"
                  :key="ind"
                  v-for="(tag,ind) in form.itemAttributeArray"
                  closable
                  :disable-transitions="false"
                  @close="handleCloseAt(tag)">
                  {{ tag }}
                </el-tag>
                <el-input style="width: 200px;"
                  class="input-new-tag"
                  v-if="inputVisibleAt"
                  v-model="inputValueAt"
                  ref="saveTagInputAt"
                  size="small"
                  @keyup.enter.native="handleInputConfirmAt"
                  @blur="handleInputConfirmAt">
                </el-input>
                <el-button v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInputAt">+新增属性
                </el-button>

              </el-form-item>
            </el-col>

          </el-row>

          <el-form-item label="项目主图"
            prop="itemMainImage">
            <imageArraySize :imageStr.sync="form.itemMainImage"
              :key="form.itemMainImage"
              ref="childsss"
              :msg="'图片要求：宽高750*750，大小2M内。'"
              :limit="1"
              :size="2 * 1024 * 1024"></imageArraySize>
          </el-form-item>

          <el-form-item label="项目背景图"
            prop="backgroundImage">
            <imageArraySize :imageStr.sync="form.backgroundImage"
              :key="form.backgroundImage"
              ref="childBackgroundImage"
              :msg="'图片要求：宽高670*180，大小2M内。'"
              :limit="1"
              :size="2 * 1024 * 1024"></imageArraySize>
          </el-form-item>

          <el-form-item label="项目轮播图"
            prop="itemBanner">
            <imageArraySize v-if="isLoad"
              :imageStr.sync="form.itemBanner"
              key="form.itemBanner"
              ref="child"
              :msg="'图片要求：宽高750*484，大小2M内。'"
              :limit="20"
              :size="2 * 1024 * 1024"></imageArraySize>
          </el-form-item>

          <!-- <el-form-item label="项目icon" prop="itemIcon">
            <imageArraySize :imageStr.sync="form.itemIcon" :key="form.itemIcon" ref="childs"
              :msg="'图片要求：宽高等于400px，大小5M内。'" :limit="1" :size="5 * 1021 * 1024"></imageArraySize>
          </el-form-item> -->

          <div class="div-text"
            v-if="displayBool == 0"
            @click="divShow(1)">添加更多 图片、文案
            <i class="el-icon-arrow-down"></i>
          </div>

          <div :class="displayBool == 0 ? 'div-img' : ''">

            <el-row :gutter="24">
              <el-col :span="22">
                <el-form-item label="项目文字描述"
                  prop="itemDescText">
                  <el-input type="textarea"
                    :rows="2"
                    v-model="form.itemDescText"
                    placeholder="请输入项目文字描述"
                    clearable
                    maxlength="200"
                    show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="项目图片"
              prop="itemDescImage">
              <imageArraySize :imageStr.sync="form.itemDescImage"
                :key="form.itemDescImage"
                ref="childss"
                :msg="'图片要求：高度自适应，大小2M内。'"
                :limit="20"
                :size="2 * 1024 * 1024"></imageArraySize>
            </el-form-item>

            <el-row :gutter="24">
              <el-col :span="22">
                <el-form-item label="特别提示"
                  prop="itemTips">
                  <el-input type="textarea"
                    :rows="2"
                    v-model="form.itemTips"
                    placeholder="请输入特别提示"
                    clearable
                    maxlength="200"
                    show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>

          </div>
          <div class="div-text"
            v-if="displayBool == 1"
            @click="divShow(0)">收起
            <i class="el-icon-arrow-up"></i>
          </div>
        </div>

        <div class="product-div-two">
          <div class="product-header">
            <em style="font-size: 18px;font-style: normal;"
              class="big_title_style">sku列表</em>
          </div>
          <div style="width: 1200px;padding: 10px 10px 20px 100px;">
            <el-button style="margin: 5px;float: right;"
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd">新增</el-button>
            <el-table :data="form.proboxServiceItemSkus"
              border>

              <el-table-column prop="skuName"
                align="center"
                label="sku名称">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.skuName"></el-input>
                </template>

              </el-table-column>
              <el-table-column prop="itemPrice"
                align="center"
                label="面价">
                <template slot-scope="scope">
                  <el-input-number style="width:96px;"
                    :precision="2"
                    :controls="false"
                    :step="0.1"
                    :min="0.01"
                    :max="9999999"
                    v-model="scope.row.itemPrice"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="itemFavorablePrice"
                align="center"
                label="活动价格(元)">
                <template slot-scope="scope">
                  <el-input-number style="width:96px;"
                    :precision="2"
                    :controls="false"
                    :step="0.1"
                    :min="0"
                    :max="9999999"
                    v-model="scope.row.itemFavorablePrice"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="isSupportCoupon"
                align="center"
                label="支持优惠券">
                <template slot-scope="scope">
                  <el-switch active-value="1"
                    inactive-value="0"
                    v-model="scope.row.isSupportCoupon">
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column prop="isUseBoluoGoldCoin"
                align="center"
                label="支持金币">
                <template slot-scope="scope">
                  <el-switch active-value="1"
                    inactive-value="0"
                    v-model="scope.row.isUseBoluoGoldCoin">
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column prop="isUseBoluoSilverCoin"
                align="center"
                label="支持银币">
                <template slot-scope="scope">
                  <el-switch active-value="1"
                    inactive-value="0"
                    v-model="scope.row.isUseBoluoSilverCoin">
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column prop="itemSettlementPrice"
                align="center"
                label="美容师耗卡">
                <template slot-scope="scope">
                  <el-input-number style="width:96px;"
                    :precision="2"
                    :controls="false"
                    :step="0.1"
                    :min="0.01"
                    :max="9999999"
                    v-model="scope.row.itemSettlementPrice"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="itemBoluoHuaPrice"
                align="center"
                label="菠萝派(个)">
                <template slot-scope="scope">
                  <el-input-number style="width:96px;"
                    :precision="0"
                    :controls="false"
                    :step="1"
                    :min="0"
                    :max="9999999"
                    v-model="scope.row.itemBoluoHuaPrice"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="itemServiceDuration"
                align="center"
                label="服务时长(分钟)"
                width="120px">
                <template slot-scope="scope">
                  <el-input-number style="width:70px;"
                    :controls="false"
                    :precision="0"
                    :step="1"
                    :min="1"
                    :max="9999999"
                    v-model="scope.row.itemServiceDuration"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="serviceTimes"
                align="center"
                label="服务次数(次)"
                width="100px">
                <template slot-scope="scope">
                  <el-input-number style="width:70px;"
                    :controls="false"
                    :precision="0"
                    :step="1"
                    :min="1"
                    :max="9999999"
                    v-model="scope.row.serviceTimes"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="dataSort"
                align="center"
                label="排序"
                width="100px">
                <template slot-scope="scope">
                  <el-input-number style="width:70px;"
                    :controls="false"
                    :precision="0"
                    :step="1"
                    :min="0"
                    :max="99"
                    v-model="scope.row.dataSort"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="操作"
                align="center"
                class-name="small-padding fixed-width"
                width="60px">
                <template slot-scope="scope">

                  <el-button size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row, scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

        </div>

      </el-form>
      <div class="dw">
        <el-button @click="colsePro"
          style="margin-top: 10px;margin-left: 40%;">返回</el-button>
        <el-button type="primary"
          @click="submitForm(0)"
          style="margin-top: 10px;">保存</el-button>
        <el-button type="primary"
          @click="submitForm(1)"
          style="margin-top: 10px;">一键上架</el-button>
      </div>
    </div>

    <commodityStore v-if="storeOpen"
      @toCloseBox="toCloseBox"
      @multipleSelection="multipleSelection"
      :flag="storeOpen"
      :source="false"
      ref="selTable"
      :serviceTypes=form.serviceTypes></commodityStore>

    <commodityDevice v-if="deviceOpen"
      @toCloseBox="toCloseDeviceBox"
      @multipleSelection="multipleSelectionDevice"
      :flag="deviceOpen"
      :itemUid="itemUid"
      :source="false"
      ref="selTableDevice"></commodityDevice>

  </div>
</template>

<script>

import {
  checkPermi,
  checkRole
}
  from "@/utils/permission"; // 权限判断函数
import {
  selectOptions
}
  from "@/api/service/serviceCategory";

import { getPayLevel } from "@/api/customer/level"
import imageArraySize from "@/components/ImageUpload/imageArraySize";
import videoUpload from "@/components/ImageUpload/videoUpload";
import sku from "@/components/sku/index"
import {
  getItem, addItem, editeItem, delSku
}
  from '@/api/service/item'

import selected from "@/components/Activity/SelectedStore";
import commodityStore from "@/components/Activity/commodityStore";

import selectedDevice from "@/components/Activity/SelectedDevice";
import commodityDevice from "@/components/Activity/commodityDevice";

export default {
  components: {
    imageArraySize,
    videoUpload,
    sku, selected,
    commodityStore, commodityDevice, selectedDevice
  },
  data () {
    return {
      serviceTypesList: [

      ],
      levelOptions: [],
      itemUid: this.$route.params.itemId,
      storeOpen: false,
      selectedDataStore: [],
      deviceOpen: false,
      selectedDataDevice: [],
      indexs: 0,
      inputVisible: false,
      inputValue: '',
      roles: 0,
      roleRule: 0,
      // th 值；动态控制 th 标题、批量设置
      //规格名称和的值, 组件里面可以添加规格名称和值
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 商品类别
      categoryOptions: [],
      itemTypeOptions: [{
        dictValue: 'Medical',
        dictLabel: '医美'
      }, {
        dictValue: 'Life',
        dictLabel: '生美'
      }],

      // 更多的下拉
      displayBool: 0,
      // 查询参数
      queryParams: {},
      columns: [],
      inputVisibleAt: false,
      inputValueAt: null,
      inputVisibleYx: false,
      inputValueYx: null,
      // 表单参数
      form: {
        itemAttributeArray: [],
        itemTagsArrayYx: [],

        serviceTypes: [],
        isCommon: '1',
        isLockDevice: '0',
        isUseBoluoGoldCoin: '0',
        isUseBoluoSilverCoin: '0',
        isUseCoupon: '0',
        isRecommend: '0',
        itemTagsArray: [],
        proboxServiceItemSkus: [],
        itemPriceStr: '0',
        itemFavorablePriceStr: '0',
        itemSettlementPriceStr: '0',
        itemBoluoHuaPriceStr: '0',
        checkList: [],
        checkListPay: [],
        memberLevel: null,
        itemSalePercent: 60,
        itemServicePercent: 40,
        isSubgift: '0',
        itemMainImage: '',
        isUseMemberDiscount: '',
        itemBanner: '',
        expireDayRadio: 0,
        isShow: '1',
      },
      property: [],
      propertyUid: [],
      // 表单校验
      rules: {
        itemBanner: [
          {
            required: true,
          }
        ],

        isLockDevice: [
          {
            required: true,
          }
        ],
        isCommon: [
          {
            required: true,
          }
        ],
        itemMainImage: [
          {
            required: true,
          }
        ],
        itemName: [{
          required: true,
          message: "项目名称不能为空",
          trigger: "blur"
        }],
        categoryUids: [{
          required: true,
          message: "项目分类不能为空",
          trigger: "blur"
        }],
        itemType: [{
          required: true,
          message: "项目类别不能为空",
          trigger: "blur"
        }],
        itemServiceDuration: [{
          required: true,
          message: "单服务耗时不能为空",
          trigger: "blur"
        }],
        itemComposeDuration: [{
          required: true,
          message: "叠加服务时长不能为空",
          trigger: "blur"
        }],
        isMaster: [{
          required: true,
          message: "请选择是否是主项目",
          trigger: "blur"
        }],
      },
      itemTypeStr: [],
      datas: [],
      tables: [],
      notNor: 0, //第一次不发生变化
      isMasterOptions: [
        {
          label: '是',
          value: '1'
        }, {
          label: '否',
          value: '0'
        }
      ],
      isLoad: false,
    };
  },
  created () {
    let $this = this
    $this.bulidSelect();
    const itemId = $this.$route.params && $this.$route.params.itemId;

    if (!itemId) {
      this.isLoad = true;
    }

  },
  activated () {
    let $this = this
    const itemId = $this.$route.params && $this.$route.params.itemId;

    if (itemId) {
      getItem(itemId).then(response => {
        let obj = JSON.parse(JSON.stringify(response.data));
        this.form = obj
        this.selectedDataStore = obj.releaseList || []
        this.selectedDataDevice = obj.deviceList || []
        // this.form.checkList = [];
        // this.form.serviceTypes = []
        this.$set(this.form, 'checkList', [])
        this.$set(this.form, 'checkListPay', [])
        this.$set(this.form, 'serviceTypes', [])
        this.$set(this.form, 'itemAttributeArray', [])
        this.$set(this.form, 'itemTagsArrayYx', [])
        if (this.form.marketingTags != "" && this.form.marketingTags != null) {
          this.form.itemTagsArrayYx = this.form.marketingTags.split(",")
        }

        if (this.form.isCommon == '0') {
          this.form.checkList.push('isCommon');
        }
        if (this.form.isLockDevice == '1') {
          this.form.checkList.push('isLockDevice');
        }
        if (this.form.isSubgift == '1') {
          this.form.checkList.push('isSubgift');
        }
        if (this.form.isShow == '1') {
          this.form.checkList.push('isShow');
        }
        if (this.form.isRecommend == '1') {
          this.form.checkList.push('isRecommend');
        }

        if (this.form.isUseCoupon == '1') {
          this.form.checkListPay.push('isUseCoupon');
        }
        if (this.form.isUseMemberDiscount == '1') {
          this.form.checkListPay.push('isUseMemberDiscount');
        }
        if (this.form.isUseBoluoGoldCoin == '1') {
          this.form.checkListPay.push('isUseBoluoGoldCoin');
        }
        if (this.form.isUseBoluoSilverCoin == '1') {
          this.form.checkListPay.push('isUseBoluoSilverCoin');
        }

        if (this.form.applyStoreType) {
          this.form.serviceTypes = this.form.applyStoreType.split(",")
        }
        //处理sku
        if (this.form.proboxServiceItemSkus) {

          this.form.proboxServiceItemSkus.forEach(vo => {
            vo.itemPrice = vo.itemPrice / 100
            vo.itemFavorablePrice = vo.itemFavorablePrice / 100
            vo.itemSettlementPrice = vo.itemSettlementPrice / 100

          })
        }

        let attArr = [];
        this.form.itemAttributeArrays.forEach(vo => {

          attArr.push(vo.attributeName)
        })
        let datasd = JSON.parse(JSON.stringify(attArr));
        this.form.itemAttributeArray = datasd;
        this.displayBool = 1;
        this.isLoad = true;
        this.itemTypeStr.push(this.form.cardType)

      });
    }
  },

  methods: {
    checkPermi,
    checkRole,
    choiceServiceCheckbox (value) {
      this.selectedDataStore = []
    },
    //复选框选中方法

    choiceCheckboxStroe (value) {
      if (!value) {
        this.selectedDataStore = []
      }
    },
    choiceCheckboxDevice (value) {
      if (!value) {
        this.selectedDataDevice = []
      }
    },
    choiceCheckboxMember (value) {
      if (!value) {
        this.form.memberLevel = null;
      }
    },
    existValue (type) {
      let index = 0;
      this.form.checkList.forEach(elemet => {
        if (elemet == type) {
          index++;
        }
      })
      return index;
    },
    existValuePay (type) {
      let index = 0;
      this.form.checkListPay.forEach(elemet => {
        if (elemet == type) {
          index++;
        }
      })
      return index;
    },
    selectCommodityDevice () {
      this.$forceUpdate()
      this.deviceOpen = true;
      this.$nextTick(() => {
        this.$refs["selTableDevice"].greet(this.selectedDataDevice);
      });
    },
    selectCommodity () {
      this.$forceUpdate()
      this.storeOpen = true;
      this.$nextTick(() => {
        this.$refs["selTable"].greet(this.selectedDataStore);
      });
    },
    multipleSelectionDevice (data) {
      this.deviceOpen = false
      this.selectedDataDevice = data;
      this.$nextTick(() => {
        this.$refs.childDevice.getList();
      });
    },
    multipleSelection (data) {
      this.storeOpen = false
      this.selectedDataStore = data;
      this.$nextTick(() => {
        this.$refs.childStore.getList();
      });
    },
    toCloseDeviceBox () {
      this.deviceOpen = false;
    },
    toCloseBox () {
      this.storeOpen = false;
    },
    indexMethod (index) {
      this.indexs = index
      return index * 1;
    },
    handleDelete (row, index) {
      if (row.skuId) {
        delSku(row.skuId).then(response => {
          this.form.proboxServiceItemSkus.splice(index, 1);

        })
      } else {
        this.form.proboxServiceItemSkus.splice(index, 1);

      }
    },
    handleAdd () {
      let data = {
        no: JSON.parse(JSON.stringify(this.indexs)),
        skuId: null,
        skuName: null,
        serviceItemId: null,
        isSupportCoupon: '0',
        isUseBoluoGoldCoin: '0',
        isUseBoluoSilverCoin: '0',
        itemPrice: 0,
        itemFavorablePrice: 0,
        itemSettlementPrice: 0,
        itemBoluoHuaPrice: 0,
        itemServiceDuration: 0,
        serviceTimes: 1,
      }
      this.form.proboxServiceItemSkus.push(data);
    },


    oninput (num, limit) {

      var str = num
      var len1 = str.substr(0, 1)
      var len2 = str.substr(1, 1)
      if (str.length > 1 && len1 == 0 && len2 != ".") {
        str = str.substr(1, 1)
      }
      if (len1 == ".") {
        str = ""
      }
      if (str.indexOf(".") != -1) {
        var str_ = str.substr(str.indexOf(".") + 1)
        if (str_.indexOf(".") != -1) {
          str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1)
        }
      }
      //正则替换
      str = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点
      if (limit / 1 === 1) {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/, '$1') // 小数点后只能输 1 位
      } else {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1') // 小数点后只能输 2 位
        if (str.indexOf(".") == str.length - 1) {
          str = str.substring(0, str.length - 1);
        }
      }
      return str
    },
    oninputs (num, limit) {

      var str = num
      var len1 = str.substr(0, 1)
      var len2 = str.substr(1, 1)
      if (str.length > 1 && len1 == 0 && len2 != ".") {
        str = str.substr(1, 1)
      }
      if (len1 == ".") {
        str = ""
      }
      if (str.indexOf(".") != -1) {
        var str_ = str.substr(str.indexOf(".") + 1)
        if (str_.indexOf(".") != -1) {
          str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1)
        }
      }
      //正则替换
      str = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点
      if (limit / 1 === 1) {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/, '$1') // 小数点后只能输 1 位
      } else {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1') // 小数点后只能输 2 位

      }
      return str
    },
    // 表单重置
    reset () {
      this.form = {};
      this.resetForm("form");
    },
    divShow (obj) {
      this.displayBool = obj;
    },
    /**各种下拉框 */
    bulidSelect () {
      // 分类
      selectOptions().then(response => {
        this.categoryOptions = response.data;
      });
      // this.getDicts("proBoxService_itemType").then(response => {
      //   this.itemTypeOptions = response.data;
      // });
      this.getDicts("item_apply_store_type").then(response => {
        this.serviceTypesList = response.data;
      });
      getPayLevel().then(response => {
        this.levelOptions = response;
      })
    },
    itemTypeChange (value) {
      this.selectedDataStore = [];
      this.form.serviceTypes = []
      this.form.serviceTypes = []
      this.form.serviceTypes.push(value);
      //  this.itemTypeStr.push(value)
    },
    disabledType (value) {
      /*
      if (value == 'Probxplus') {
        return false;
      }
      if (value != this.form.itemType) {
        return true;
      }*/
      return false
    },
    /** 提交按钮 */
    submitForm (status) {
      this.$refs.child.selectImgs();
      // this.$refs.childs.selectImg();
      this.$refs.childss.selectImg();
      this.$refs.childsss.selectImg();
      this.$refs.childBackgroundImage.selectImg();
      if (this.form.itemMainImage == null || this.form.itemMainImage == "") {
        this.$message.error("请上传一张项目主图");
        return;
      }
      if (this.form.itemBanner == null || this.form.itemBanner == "") {
        this.$message.error("请上传一张banner图片");
        return;
      }

      if (this.form.expireDayRadio == 0) {
        if (!this.form.expireDay) {
          this.$message.error("请选择有效天数!");
          return;
        }
        this.form.expireDate = null

      } else if (this.form.expireDayRadio == 2) {
        if (!this.form.expireDate) {
          this.$message.error("请选择指定时间!");
          return;
        }
      } else if (this.form.expireDayRadio == -1) {
        this.form.expireDate = null
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
          //处理sku
          if (this.form.proboxServiceItemSkus) {
            let ind = 0;
            let index = 0
            this.form.proboxServiceItemSkus.forEach(vo => {
              if (vo.itemFavorablePrice > vo.itemPrice) {
                ind++
              }
              if (vo.itemFavorablePrice) {
                if (vo.itemSettlementPrice > vo.itemFavorablePrice) {
                  index++
                }
              }

            })
            if (ind > 0) {
              this.$message.error('面价要大于等于活动价格');
              return;
            }
            // if (index > 0) {
            //   this.$message.error('活动价格要大于等于美容师耗卡');
            //   return;

            // }
            this.form.proboxServiceItemSkus.forEach(vo => {
              vo.itemPrice = vo.itemPrice * 100
              vo.itemFavorablePrice = vo.itemFavorablePrice * 100
              vo.itemSettlementPrice = vo.itemSettlementPrice * 100
            })
          }

          let qf = [];
          this.selectedDataStore.forEach(vo => {
            qf.push(vo.storeUid);
          })
          let qfDevice = [];
          this.selectedDataDevice.forEach(vo => {
            qfDevice.push(vo.deviceId);
          })
          this.form.deviceIdS = qfDevice;
          this.form.shopListIds = qf;
          const itemId = this.$route.params && this.$route.params.itemId;
          this.form.itemId = itemId;
          this.form.itemPriceView = this.form.itemPriceStr
          this.form.itemFavorablePriceView = this.form.itemFavorablePriceStr
          this.form.itemSettlementPriceView = this.form.itemSettlementPriceStr
          this.form.itemBoluoHuaPriceView = this.form.itemBoluoHuaPriceStr
          this.form.auditStatus = status;
          //多选框赋值
          if (this.form.checkList.length > 0) {
            if (this.handleCheckbox() > 0) {
              return;
            }
          } else {
            this.form.isCommon = '1'
            this.form.isLockDevice = '0'
            this.form.isRecommend = '0'
            this.form.isSubgift = '0'

          }
          let attArr = [];


          if (this.form.checkListPay.length > 0) {
            if (this.handleCheckboxPay() > 0) {
              return;
            }
          } else {
            this.form.isUseBoluoGoldCoin = '0'
            this.form.isUseBoluoSilverCoin = '0'
            this.form.isUseMemberDiscount = '0'
            this.form.isUseCoupon = '0'
            this.form.memberLevel = null
          }
          //服务类别
          if (this.form.serviceTypes) {
            let s = ""
            this.form.serviceTypes.forEach(str => {
              s += "," + str;
            })
            this.form.applyStoreType = s.substring(1);
          }

          if (this.form.itemTagsArrayYx) {
            let s = ""
            this.form.itemTagsArrayYx.forEach(str => {
              s += "," + str;
            })
            this.form.marketingTags = s.substring(1);
          }


          this.form.itemAttributeArray.forEach(vo => {
            let data = {
              attributeName: vo
            }
            attArr.push(data)
          })
          this.form.itemAttributeArrays = attArr;
          if (itemId) {
            editeItem(this.form).then(respone => {
              this.msgSuccess("修改成功");
              this.colsePro();
            })
          } else {
            addItem(this.form).then(respone => {
              this.msgSuccess("添加成功");
              this.colsePro();
            })
          }
        }
      });
    },//多选框的传值
    handleCheckbox () {
      if (this.form.checkList.includes('isCommon')) {
        this.form.isCommon = '0'
      } else {
        this.form.isCommon = '1'
      }
      if (this.form.checkList.includes('isLockDevice')) {
        this.form.isLockDevice = '1'
      } else {
        this.form.isLockDevice = '0'
      }
      if (this.form.checkList.includes('isRecommend')) {
        this.form.isRecommend = '1'
      } else {
        this.form.isRecommend = '0'
      }
      if (this.form.checkList.includes('isSubgift')) {
        this.form.isSubgift = '1'
      } else {
        this.form.isSubgift = '0'
      }
      if (this.form.checkList.includes('isShow')) {
        this.form.isShow = '1'
      } else {
        this.form.isShow = '0'
      }
      if (this.form.isCommon == '0') {
        if (this.selectedDataStore.length == 0) {
          this.$message.error("请选择一个门店");
          return 1;
        }
      }

      if (this.form.isLockDevice == '1') {
        if (this.selectedDataDevice.length == 0) {
          this.$message.error("请选择一个设备");
          return 1;
        }
      }

      //return 0;
    },
    handleCheckboxPay () {
      if (this.form.checkListPay.includes('isUseBoluoGoldCoin')) {
        this.form.isUseBoluoGoldCoin = '1'
      } else {
        this.form.isUseBoluoGoldCoin = '0'
      }
      if (this.form.checkListPay.includes('isUseBoluoSilverCoin')) {
        this.form.isUseBoluoSilverCoin = '1'
      } else {
        this.form.isUseBoluoSilverCoin = '0'
      }

      if (this.form.checkListPay.includes('isUseMemberDiscount')) {
        this.form.isUseMemberDiscount = '1'
      } else {
        this.form.isUseMemberDiscount = '0'
        this.form.memberLevel = null;
      }
      if (this.form.checkListPay.includes('isUseCoupon')) {
        this.form.isUseCoupon = '1'
      } else {
        this.form.isUseCoupon = '0'
      }

      if (this.form.isUseMemberDiscount == '1') {
        if (!this.form.memberLevel) {
          this.$message.error("请选择一个折扣等级");
          return 1;
        }
      }
      //return 0;
    },
    colsePro () {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({
        path: "/product/item",
        query: {
          t: Date.now()
        }
      });
    },
    handleClose (tag) {
      this.form.itemTagsArray.splice(this.form.itemTagsArray.indexOf(tag), 1);
    },
    handleCloseAt (tag) {
      let as = tag + "";
      this.form.itemAttributeArray.splice(this.form.itemAttributeArray.indexOf(as), 1);
      console.log(this.form.itemAttributeArray)

    },
    handleCloseYx (tag) {
      this.form.itemTagsArrayYx.splice(this.form.itemTagsArrayYx.indexOf(tag), 1);
    },
    showInput () {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    showInputAt () {
      this.inputVisibleAt = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInputAt.$refs.input.focus();
      });
    },
    showInputYx () {
      this.inputVisibleYx = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInputYx.$refs.input.focus();
      });
    },
    handleInputConfirm () {
      let inputValue = this.inputValue;
      //判断是否已经存在
      if (this.form.itemTagsArray.indexOf(inputValue) > -1) {
        this.$message.error("标签重复！重新输入");
      } else {
        if (inputValue) {
          this.form.itemTagsArray.push(inputValue);
        }
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    handleInputConfirmAt () {
      let inputValue = this.inputValueAt;
      //判断是否已经存在
      if (this.form.itemAttributeArray.indexOf(inputValue) > -1) {
        this.$message.error("标签重复！重新输入");
      } else {
        if (inputValue) {
          this.form.itemAttributeArray.push(inputValue);
        }
      }
      this.inputVisibleAt = false;
      this.inputValueAt = '';
    }, handleInputConfirmYx () {
      let inputValue = this.inputValueYx;
      //判断是否已经存在
      if (this.form.itemTagsArrayYx.indexOf(inputValue) > -1) {
        this.$message.error("标签重复！重新输入");
      } else {
        if (inputValue) {
          this.form.itemTagsArrayYx.push(inputValue);
        }
      }
      this.inputVisibleYx = false;
      this.inputValueYx = '';
    }
  }
};
</script>
<style scoped>
#container {
  width: 100%;
  height: 50%;
}

#photo {
  float: left;
  width: 70%;
}

#content {
  float: right;
  width: 30%;
}

.product-header {
  position: absolute;
  top: 0;
  width: 600px;
  padding: 18px;
  background-color: #fff;
  -moz-border-radius: 4px;
  border-radius: 4px;
  height: 40px;
}

.product-div {
  background-color: #fff;
  position: relative;
  padding-right: 16px;
  padding-top: 54px;
  border: 1px solid #ebebeb;
  -moz-border-radius: 10px;
  border-radius: 10px;
  width: 1200px;
  margin: auto;
  top: 20px;
  bottom: -20px;
  margin-bottom: 50px;
}

.product-div-two {
  background-color: #fff;
  position: relative;
  padding-right: 16px;
  padding-top: 54px;
  border: 1px solid #ebebeb;
  -moz-border-radius: 10px;
  border-radius: 10px;
  width: 1200px;
  margin: auto;
  top: 20px;
  bottom: -20px;
  margin-bottom: 60px;
}

.product-div-three {
  background-color: #fff;
  position: relative;
  padding-right: 16px;
  padding-top: 54px;
  border: 1px solid #ebebeb;
  -moz-border-radius: 10px;
  border-radius: 10px;
  width: 1200px;
  margin: auto;
  top: 20px;
  bottom: -20px;
  margin-bottom: 100px;
}

.place-font {
  color: #999;
  font-size: 13px;
  position: relative;
}

.dw {
  border: 1px;
  position: fixed;
  bottom: 0px;
  left: 0;
  z-index: 200;
  padding-left: 120px;
  background-color: #fff;
  border-top: 1px solid #eee;
  width: 100%;
  height: 55px;
}

.div-img {
  display: none;
}

.div-text {
  margin: 22px 0px 12px 120px;
  color: #2656bd;
  cursor: pointer;
  font-size: 13px;
}

.div-append {
  line-height: 34px;
  font-size: 14px;
  color: #606266;
  margin-left: -50%;
}

.div-appendHide {
  line-height: 34px;
  font-size: 14px;
  color: #606266;
  margin-left: -50%;
  visibility: hidden;
}
</style >
